home *** CD-ROM | disk | FTP | other *** search
- Path: news.iag.net!news
- From: jatmon@iag.net (John R Buchan)
- Newsgroups: comp.lang.c
- Subject: Re: Mem Allocation in functions
- Date: 14 Jan 1996 18:58:42 GMT
- Organization: Internet Access Group, Orlando, Florida
- Message-ID: <4dbjp2$47c@news.iag.net>
- References: <00001a80+00006ba7@msn.com>
- NNTP-Posting-Host: pm3-orl13.iag.net
- X-Newsreader: WinVN 0.99.7
-
- In article <00001a80+00006ba7@msn.com>, Gordon_B@msn.com says...
- >
- >I should know the answer, but I don't. I have a function
- >
- >#include <usual stuff>
- > void foo(float *stuff, int *length)
- > {
- > int i;
- > stuff = calloc(*length, sizeof(float));
- >// diddle around and put numbers in stuff[i]
- > return;
- > }
- >//
- > int main(void)
- > {
- > int count;
- > float *somenums;
- > int np = 20;
- > void foo(float *, int *);
- > foo(somenums,&np);
- > for(count = 0 ; count < np ; count++)
- > fprintf(stdout,"%4d %10.2f\n",count, somenums[count] ;
- > free(somenums);
- > return 0;
- > }
- >My question is: in foo, memory was allocated to the pointer "somenums" and
- >at the return the array was filled with the correct values. However,
- >in main the array is junk NANs, and in fact the pointer is pointing into DS.
- >On the other hand, if "somenums" is calloc'd in main, correct values are
- >obtained.
-
- The problem is that you are passing a copy of the value of somenums to
- foo, not a pointer to somenums. For a function to modify the value of an
- object that is out of scope to the function, the function must have a pointer
- to that object. So change your function definition to accept a pointer
- to a pointer to a float (float **stuff), modify your allocation statement to
- assign the return of calloc to the object pointed to by stuff (*stuff), and
- call the function by passing the address of the pointer you want modified
- (&somenums).
-
- BTW, if you are going to need to dereference stuff often in foo, you may find
- it easier to troubleshoot, if you define a local pointer, assign the alloc
- return to it, use it to do any testing and modifications, then just before
- exiting the function assign its value to the object pointed to by your param.
- This requires the use of an unnecessary local variable, but, IMHO,it makes
- the code much easier to read, if you don't happen to live for indirections.
-
- void foo( float **stuff, int *length)
- {
- float *ptr = calloc( *length, sizeof(float));
- if( ptr == NULL)
- /* handle the allocation error */
- /* use ptr to manipulate the element values */
- *stuff = ptr;
- }
-
- --
- John R Buchan -:|:- Looking for that elusive FAQ? ftp to:
- jatmon@mail.iag.net -:|:- rtfm.mit.edu /pub/usenet-by-group/....
-
-